﻿
/**
* 命名空间: Game.TDBehaviorTree
*
* 功 能： 随机节点
* 类 名： NodeRandom
*
* Ver 变更日期 负责人 变更内容
* ───────────────────────────────────
* V0.01 2019/12/11 16:10:13  
*/




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Game.TDBehaviorTree
{
    [System.Serializable]
    /// <summary>
    /// 随机节点(组合节点)
    /// </summary>
    public class NodeRandom : NodeCombine
    {
        private NodeBase m_LastNode;

        public NodeRandom() : base(NodeType.Random)
        {

        }

        public override NodeResultType Execute()
        {
            //得到随机下标List
            List<int> randomList = GetRandom(m_childNodes.Count);

            int index = -1;
            if (m_LastNode != null)
            {
                index = m_LastNode.NodeIndex;
            }
            m_LastNode = null;

            NodeResultType resultType = NodeResultType.Fail;


            while ((randomList.Count > 0))
            {
                if (index < 0)
                {
                    index = randomList[randomList.Count - 1];  //得到最后一个下标
                    randomList.RemoveAt(randomList.Count - 1);  //移除最后一个下标
                }

                NodeBase _node = m_childNodes[index];

                index = -1;

                resultType = _node.Execute();

                if (resultType == NodeResultType.Fail)
                {
                    continue;
                }

                if (resultType == NodeResultType.Success)
                {
                    break;
                }

                if (resultType == NodeResultType.Running)
                {
                    m_LastNode = _node;
                    break;
                }
            }

            return resultType;

        }


        /// <summary>
        /// 给出随机排序List
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        private List<int> GetRandom(int count)
        {
            List<int> resultList = new List<int>(count);
            List<int> tempList = new List<int>();

            for (int i = 0; i < count; ++i)
            {
                tempList.Add(i);
            }

            System.Random random = new System.Random();
            while (tempList.Count > 0)
            {
                int index = random.Next(0, (tempList.Count - 1));
                resultList.Add(tempList[index]);
                tempList.RemoveAt(index);
            }

            return resultList;
        }

    }
}

